package com.example.analysis.service.impl;

import com.example.analysis.domain.ScoreInfo;
import com.example.analysis.domain.SemesterStatistic;
import com.example.analysis.entity.Class;
import com.example.analysis.entity.Election;
import com.example.analysis.entity.PageBean;
import com.example.analysis.mapper.ElectionDao;
import com.example.analysis.service.ElectionService;
import com.example.analysis.utils.Response;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ElectionServiceImpl implements ElectionService {
    @Resource
    private ElectionDao electionDao;

    @Override
    public Response<Election> insert(Election aElectionList) {
        try {
            electionDao.insert(aElectionList);
            return new Response<>(true, "Insert success", null);
        } catch (Exception e) {
            return new Response<>(false, "Insert failed: " + e.getMessage(), null);
        }
    }

    @Override
    public Response<Election> getById(String subId,String studentId) {
        Election aElectionList = electionDao.selectByPrimaryKey(subId,studentId);
        if (aElectionList != null) {
            return new Response<>(true, "Success", aElectionList);
        } else {
            return new Response<>(false, "Administration not found", null);
        }
    }

    @Override
    public Response<Election> getByName(String ElectionListName) {
        Election aElectionList = electionDao.selectByName(ElectionListName);
        if (aElectionList != null) {
            return new Response<>(true, "Success", aElectionList);
        } else {
            return new Response<>(false, "Administration not found", null);
        }
    }

    @Override
    public PageBean getAll(Integer pageNum, Integer pageSize) {

        PageHelper.startPage(pageNum,pageSize);
        List<ScoreInfo> scoreInfoList=electionDao.getAll();
        Page p=(Page) scoreInfoList;
        long total=p.getTotal();
        List result=p.getResult();
        PageBean pageBean=new PageBean();
        pageBean.setTotal(total);
        pageBean.setRows(result);//返回总条数和具体数据
        return pageBean;
    }

    @Override
    public List<ScoreInfo> getData() {
        List<ScoreInfo> scoreInfoList=electionDao.getAll();
        return scoreInfoList;
    }

    @Override
    public List<ScoreInfo> getCourse(String semester) {
        List<ScoreInfo> scoreInfoList=electionDao.getCourse(semester);
        return scoreInfoList;
    }

    @Override
    public List<Class> getByClassId(String subId) {
        List<Class> scoreInfoList=electionDao.getByClassId(subId);
        return scoreInfoList;
    }

    @Override
    public List<ScoreInfo> getSelectAll(String selectCourseId, String selectClassId) {
        List<ScoreInfo> scoreInfoList=electionDao.getSelectAll(selectCourseId,selectClassId);
        return scoreInfoList;
    }

    @Override
    public List<ScoreInfo> getList(ScoreInfo scoreInfo) {

        List<ScoreInfo> list=electionDao.getList(scoreInfo);
        return list;
    }

    @Override
    public List<ScoreInfo> diffClass(ScoreInfo scoreInfo) {
        //处理成绩数据  获取要处理的数据
        List<ScoreInfo> list1=electionDao.getList(scoreInfo);
            List<ScoreInfo> result = list1.stream().collect(Collectors.groupingBy(
                    ScoreInfo::getClassId,
                    // 对每个分组计算平均值，生成新的ScoreInfo对象
                Collectors.collectingAndThen(
                    Collectors.toList(),
                    list -> {
                        // 计算总分、期末、平时、期中的总和
                        double totalSum = 0, totalScore = 0, totalDay = 0, totalMid = 0;
                        for (ScoreInfo s : list) {
                            totalSum += s.getSumScore();
                            totalScore += s.getScore();
                            totalDay += s.getDayScore();
                            totalMid += s.getHalfScore(); // 假设原期中字段为halfScore
                        }
                        // 计算平均值
                        int count = list.size();
                        ScoreInfo temp=new ScoreInfo();
                        temp.setClassName(list.get(0).getClassName());
                        temp.setClassId(list.get(0).getClassId());
                        temp.setScore((double) Math.round(totalScore / count*100)/100);
                        temp.setDayScore((double) Math.round(totalDay / count*100)/100);
                        temp.setHalfScore((double) Math.round(totalMid / count*100)/100);
                        temp.setSumScore((double) Math.round(totalSum / count*100)/100);
                        return temp;
                    }
                )
            ))
            .values().stream()
            .collect(Collectors.toList());
            return result;
    }


    //某一门课程在不同学期的情况    列举出期末成绩的及格率低于60%的班级
    @Override
    public List<SemesterStatistic> diffSemester(ScoreInfo scoreInfo) {
        //处理成绩数据  获取要处理的数据
        List<ScoreInfo> list1=electionDao.getList(scoreInfo);
        List<SemesterStatistic> result=list1.stream().collect(Collectors.groupingBy(
                ScoreInfo::getSemester,
                Collectors.collectingAndThen(
                        Collectors.toList(),
                        list -> {
                            int total = list.size();
                            long passed = list.stream()
                                    .filter(si -> si.getScore() >= 60)
                                    .count();
                            double passRate = total == 0 ? 0 : (double) passed / total * 100;
                            double avgSumScore = list.stream()
                                    .mapToDouble(ScoreInfo::getSumScore)
                                    .average()
                                    .orElse(0.0);
                            SemesterStatistic semesterStatistic=new SemesterStatistic();
                            semesterStatistic.setSemester(list.get(0).getSemester());
                            semesterStatistic.setAvgScore((double) Math.round(avgSumScore*100)/100);
                            semesterStatistic.setPassRate((double) Math.round(passRate*100)/100);
                            return semesterStatistic;
                        }
                )
        ))
                .values().stream()
                .collect(Collectors.toList());;
        return result;
    }
}
